package com.website.dayouziblog.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.website.dayouziblog.exception.BaseErrorEnum;
import com.website.dayouziblog.exception.BaseException;
import com.website.dayouziblog.model.DO.UserDO;
import com.website.dayouziblog.model.DTO.UserDTO;
import com.website.dayouziblog.model.VO.UserVO;
import com.website.dayouziblog.model.entity.PageBean;
import com.website.dayouziblog.mapper.dayouziblog.UserMapper;
import com.website.dayouziblog.service.UserService;
import com.website.dayouziblog.utils.RedisUtil;
import com.website.dayouziblog.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${key.user_token}")
    private String user_token;

    @Value("${key.user_lock}")
    private String user_lock;

    @Value("${key.user_pwd_num}")
    private Integer user_pwd_num;

    @Value("${key.user_token_expireTime}")
    private Integer user_token_expireTime;

    @Value("${key.user_expireTime}")
    private Integer user_expireTime;

    @Override
    public Boolean registIn(UserDTO userDTO) {
        //先判断是否存在该用户
        UserDO userDO = userMapper.getInfoByAccount(userDTO.getUserAccount());
        if (userDO != null){
            throw new BaseException(BaseErrorEnum.USER_IS_EXISTS);
        }

        //新增用户
        userMapper.registIn(userDTO);
        return true;
    }

    @Override
    public PageBean findAllUser(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        return new PageBean<>(userMapper.findAllUser());
    }

    @Override
    public UserVO login(UserDTO userDTO) {

        //判断用户是否被锁定
        String key = user_lock + userDTO.getUserAccount();
        Integer pwdErrorNums = 0;
        if (redisUtil.hasKey(key)) {
            pwdErrorNums = (Integer) redisUtil.get(key);
        }
        if (pwdErrorNums > user_pwd_num) {
            LOGGER.error("该用户已被锁定");
            throw new BaseException(BaseErrorEnum.USER_NAME_LOCK);
        }

        //先获取用户
        UserDO userDO = userMapper.getInfoByAccount(userDTO.getUserAccount());
        if (userDO == null) {
            throw new BaseException(BaseErrorEnum.USER_NOT_EXISTS);
        } else {
            //再验证密码
            if (!userDO.getPassword().equals(userDTO.getPassword())) {
                //密码错误
                pwdErrorNums++;
                redisUtil.set(key, pwdErrorNums);
                throw new BaseException(BaseErrorEnum.PASSWORD_ERROR);
            } else {
                //删除密码错误统计的次数
                redisUtil.del(key);
                //生成token
                String token = TokenUtils.sign(userDO);
                //将token放入redis
                redisUtil.set(user_token + userDO.getUserAccount(), token, user_token_expireTime);
                //DO转VO
                UserVO userVO = JSONObject.parseObject(JSONObject.toJSONString(userDO), UserVO.class);
                userVO.setToken(token);
                LOGGER.info("登录成功");
                return userVO;
            }
        }
    }

    @Override
    public Boolean deleteUser(String id) {
        //先判断是否存在该用户
        if (!userMapper.isExists(id)) {
            throw new BaseException(BaseErrorEnum.USER_NOT_EXISTS);
        }

        //删除用户
        return userMapper.deleteUser(id);
    }

    @Override
    public Boolean updateUser(UserDTO userDTO) {
        //先判断是否存在该用户
        if (!userMapper.isExists(userDTO.getId())) {
            throw new BaseException(BaseErrorEnum.USER_NOT_EXISTS);
        }

        //修改用户
        return userMapper.updateUser(userDTO);
    }
}
